package com.atguigu.jinx.utils;

import com.atguigu.jinx.entity.pojo.TwilioProperties;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TwilioSmsSender {

    private final TwilioProperties twilioProperties;


    @Autowired
    public TwilioSmsSender(TwilioProperties twilioProperties) {
        this.twilioProperties = twilioProperties;
        Twilio.init(twilioProperties.getAccountSid(), twilioProperties.getAuthToken());
    }

    /**
     * 生成随机验证码
     *
     * @param length 验证码长度
     * @return 随机验证码
     */
    public static String generateRandomCode(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append((int) (Math.random() * 10));
        }
        return sb.toString();
    }

    /**
     * 发送短信
     *
     * @param toPhoneNum 接收方手机号（如 +1234567890）
     * @param content    短信内容
     */
    public boolean sendSms(String toPhoneNum, String code, String template) {

        String phoneNum = addInternationalPrefix(toPhoneNum);
        // 构建模板
        String content = template.concat(code);
        Message message = Message.creator(
                new PhoneNumber(phoneNum),
                new PhoneNumber(twilioProperties.getFromPhoneNum()),
                content
        ).create();
        return message.getErrorCode() == null;
    }

    /**
     * 添加国际区号(中国;日本)
     *
     * @param toPhoneNum 手机号
     * @return 区号+手机号
     */
    private String addInternationalPrefix(String toPhoneNum) {
        if (StringUtils.isNoneBlank(toPhoneNum)) {

            if (toPhoneNum.startsWith("0")) {
                return "+81".concat(toPhoneNum);
            }

            if (toPhoneNum.startsWith("1")) {
                return "+86".concat(toPhoneNum);
            }
        }
        return "";
    }
}
